/*
 * @Author: hongbin
 * @Date: 2021-11-09 16:34:59
 * @LastEditors: hongbin
 * @LastEditTime: 2021-11-16 11:05:45
 * @Description: 连接数据库对话框
 */
import {
  Card,
  CardContent,
  TextField as MTextField,
  styled,
} from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { FC, ReactElement, useRef, useState, ChangeEvent, memo } from "react";
import { ConnectedTv } from "@mui/icons-material";
import { ConnectParams, DbInfo } from "../../api/types";
import { NoticeRef } from "../Notice";
import { connect } from "../../api/mongo";

const TextField = styled(MTextField)`
  margin-bottom: 0.5rem;
`;

const initConnect: ConnectParams = {
  host: "159.75.22.82",
  port: "27017",
  username: "",
  password: "",
  tableName: "mywebsite",
};

interface IProps {
  handleConnect: (info: DbInfo) => void;
}

const Connect: FC<IProps> = ({ handleConnect }): ReactElement => {
  const [loading, setLoading] = useState(false);
  const info = useRef<ConnectParams>(initConnect);

  const createConnect = async () => {
    const { current: params } = info;
    if (!params.host || !params.port)
      return NoticeRef.current?.open({
        message: "地址和端口必填",
        type: "error",
      });
    setLoading(true);
    const { data } = await connect(params);
    if (data) {
      console.log(data);
      const { id, dbs, databaseName } = data;
      handleConnect({ id, dbs, databaseName });
    }
    setLoading(false);
  };

  const setFields = (key: string) => (e: ChangeEvent<HTMLInputElement>) => {
    info.current = { ...info.current, [key]: e.target.value };
  };

  return (
    <Card>
      <CardContent>
        <TextField
          label="服务器地址"
          variant="standard"
          placeholder="例:159.75.22.82"
          onChange={setFields("host")}
          helperText="必填"
          defaultValue="159.75.22.82"
        />
        <TextField
          label="服务器端口"
          variant="standard"
          type="number"
          placeholder="27017"
          onChange={setFields("port")}
          helperText="必填"
          defaultValue="27017"
        />
        <TextField
          label="数据库名"
          variant="standard"
          onChange={setFields("tableName")}
        />
        <TextField
          label="用户名"
          variant="standard"
          onChange={setFields("username")}
          helperText="不会记录你的信息"
        />
        <TextField
          label="密码"
          variant="standard"
          type="password"
          onChange={setFields("password")}
        />
        <br />
        <LoadingButton
          loading={loading}
          loadingPosition="start"
          startIcon={<ConnectedTv />}
          variant="outlined"
          onClick={createConnect}
        >
          创建连接
        </LoadingButton>
      </CardContent>
    </Card>
  );
};

export default memo(Connect);
